<template>
    <n-scrollbar style="max-height: 100vh" x-scrollable>
        <CommonPage show-footer>
            <div>
                <form>
                    <div style="display: flex;margin-top: -30px; align-items: center">
                        <n-form-item>
                            <label style="width: 70px;">活动名称：</label>
                            <n-input v-model:value="searchCondition.name" clearable placeholder="输入活动名称"
                                     style="width: 170px;"/>
                        </n-form-item>
                        <n-form-item style="margin-left: 10px">
                            <label style="width: 60px;">店铺名：</label>
                            <n-input v-model:value="searchCondition.shopName" clearable placeholder="输入店铺名"
                                     style="width: 170px;"/>
                        </n-form-item>
                        <n-form-item style="margin-left: 10px">
                            <label style="width: 50px;">创建人:</label>
                            <n-select v-model:value="searchCondition.adminId" :options="admins"/>
                        </n-form-item>
                        <n-form-item>
                            <n-button style="margin-left: 20px"
                                      type="primary"
                                      @click="searchByCondition">
                                筛选
                            </n-button>
                        </n-form-item>
                        <n-form-item>
                            <n-button style=" margin-left: 10px"
                                      type="primary"
                                      @click="showForm=true">
                              添加促销活动
                            </n-button>
                        </n-form-item>
                      <n-form-item>
                        <n-button style="margin-left: 10px"
                                  type="error"
                                  @click="deleteSelectSalePromotion">
                          批量删除
                        </n-button>
                      </n-form-item>
                      <n-form-item>
                        <n-button style="margin-left: 10px" type="primary" @click="exportListInfo">
                          导出
                        </n-button>
                      </n-form-item>
                    </div>
                </form>
              <AddSalePromotionForm
                  :shopOptions="shops"
                  :storeCommodityOptions="storeCommodity"
                  @update-page="searchByCondition"
                  :show="showForm"
                  :onClose="handleClose"/>
              <UpdateSalePromotionForm
                  :shopOptions="shops"
                  :storeCommodityOptions="storeCommodity"
                  @update-page="searchByCondition"
                  :show="showForm1"
                  :onClose="handleClose"
                  :attribute="currentAttribute"
              />
              <n-data-table
                  ref="table"
                  :columns="columns"
                  :data="salePromotionActivityList"
                  :loading="loading"
                  :pagination="paginationReactive"
                  :row-key="rowKey"
                  :scroll-x="900"
                  :single-line="false"
                  remote
                  @update:checked-row-keys="handleCheck"
              />
            </div>
        </CommonPage>
    </n-scrollbar>
</template>

<script setup>
import {onMounted, reactive, ref} from 'vue'
import api from '@/api/admin';

import {useUserStore} from '@/store';
import {useRouter} from 'vue-router';
import SalePromotionActions from './components/sale-promotion-actions.vue';
import AddSalePromotionForm from './components/sale-promotion-add.vue'
import UpdateSalePromotionForm from './components/sale-promotion-edit.vue'

const showForm = ref(false);
const showForm1 = ref(false);
const searchCondition = ref({
  name: '',
  shopName: '',
  adminId: -1,
})
const handleClose = () => {
  showForm.value = false;
  showForm1.value = false;
};
const currentAttribute = ref(null); // 当前编辑的属性
const userStore = useUserStore()
const router = useRouter()
const loading = ref(true)
const salePromotionActivityList = ref([])
const range = ref(null)
const admins = ref([])
const shops = ref([])
const storeCommodity = ref([])
admins.value.push({
    label: '全部',
    value: -1,
})
const checkedRowKeysRef = ref([]);
const handleCheck = (rowKeys) => {
    checkedRowKeysRef.value = rowKeys;
}
const columns = [
  {
    type: 'selection',
    fixed: 'left',
  },
  {
    key: 'colId',
    title: '序号',
    width: 40,
  },
  {
    key: 'id',
    title: '活动编号',
    width: 50,
  },
  {
    key: 'name',
    title: '活动名称',
    width: 100,
  },
  {
    key: 'rule',
    title: '规则',
    width: 100,
  },
  {
    key: 'shopName',
    title: '店铺名',
    width: 100,
  },
  {
    key: 'storeCommodityName',
    title: '指定货物',
    width: 200,
  },
  {
    key: 'promotionRate',
    title: '折扣力度',
    width: 60,
  },
  {
    key: 'startTime',
    title: '开始时间',
    width: 100,
  },
  {
    key: 'endTime',
    title: '截止时间',
    width: 100,
  },
  {
    key: 'adminName',
    title: '创建人',
    width: 100,
  },
  {
    key: 'createTime',
    title: '创建时间',
    width: 100,
  },
  {
    key: 'do',
    title: '操作',
    width: 130,
    render(row) {
      return h(
          SalePromotionActions,
          {
            onClickEdit: () => onEditSalePromotion(row),
            onClickDelete: () => onDeleteSalePromotion(row),
                }
            );
        }
    },


]
const onDeleteSalePromotion = (row) => {
  $dialog.warning({
    title: '警告',
    content: '您确定删除此促销活动？',
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: async () => {
      loading.value = true
      try {
        const res = await api.deleteSalePromotionActivity({ id: row.id})
        if (res.code === 200) {
          $message.success("删除促销活动成功！")
          await queryByPage()
        }
        else {
          $message.error(res.message)
        }
      } catch (err) {
        $message.error("删除促销活动失败！")
      } finally {
        loading.value = false
      }
    }
  })
}

const onEditSalePromotion = async (salePromotion) => {
  currentAttribute.value = salePromotion; // 设置当前编辑的属性
  showForm1.value = true; // 显示编辑窗口
}
let total = 0
const paginationReactive = reactive({
    page: 1,
    pageSize: 50,
    showSizePicker: true,
    pageSizes: [50, 100, 150],
    itemCount: 0,
    prefix: () => {
        return '查询出 ' + total + '条记录';
    },
    onChange: (page) => {
        paginationReactive.page = page;
        queryByPage()
    },
    onUpdatePageSize: (pageSize) => {
        paginationReactive.pageSize = pageSize;
        paginationReactive.page = 1;
        queryByPage()
    }
});
const productInfoValue = ref({
    name: '',
    id: '',
    pageNum: paginationReactive.page,
    pageSize: paginationReactive.pageSize

});
const deleteSelectSalePromotion = () => {
    if (checkedRowKeysRef.value.length <= 0) {
        $message.error("当前并未选择促销活动！")
        return
    }
    $dialog.confirm({
        title: '警告',
        content: '您确定删除当前所选促销活动？',
        positiveText: '确定',
        negativeText: '取消',
        onPositiveClick: async () => {
            const ids = checkedRowKeysRef.value.join(",")
            loading.value = true
            try {
                const res = await api.deleteSalePromotionActivities({ params: { ids } })
                if (res.code === 200) {
                    $message.success("删除所选促销活动成功！")
                    await searchByCondition()
                } else {
                    $message.error(res.message)
                }
            } catch (err) {
                $message.error("删除所选促销活动失败！")
            } finally {
                loading.value = false
            }
        },
    })
}
const searchByCondition = async () => {
    loading.value = true
    try {
        paginationReactive.page = 1;
        const res = await api.findPageSalePromotionActivity({
            params: {
                ...searchCondition.value,
                pageNum: paginationReactive.page,
                pageSize: paginationReactive.pageSize,
            }
        })
        if (res.code === 200) {
            total = res.data.total
            paginationReactive.itemCount = total
            const baseCount = (paginationReactive.page - 1)*paginationReactive.pageSize
            salePromotionActivityList.value = res.data.records.map((item,i)=>{
                return {...item,
                    colId: baseCount + i + 1,
                }
            })
        } else {
            $message.error(res.message)
        }
    } catch (err) {
        $message.error("查询促销活动失败！")
    } finally {
        loading.value = false
    }
}
const exportListInfo = async () => {
  const res = await api.exportSalePromotionActivities({
    name: searchCondition.value.name,
    shopName: searchCondition.value.shopName,
    adminId: searchCondition.value.adminId,
  });
  const contentDisposition = res.headers["content-disposition"]
  let original_fileName = ""
  if(contentDisposition) {
    const uri = res.headers["content-disposition"].split("=")[1]
    original_fileName = window.decodeURI(uri)
  }
  const blob = new Blob([res.data], {type: "application/vnd.ms-excel"});
  if(window.navigator && window.navigator.msSaveOrOpenBlob) {
    window.navigator.msSaveOrOpenBlob(blob, original_fileName);
  } else{
    const fileName = original_fileName;
    const elink = document.createElement('a')
    document.body.appendChild(elink)
    elink.download= fileName;
    elink.style.display ="none"
    elink.href  = window.URL.createObjectURL(blob)
    elink.click()
    window.URL.revokeObjectURL(elink.href)
    document.body.removeChild(elink)
  }
}
const onDeleteLog = async (log) => {
    $dialog.confirm({
        title: '警告',
        content: '您确定删除当前促销活动？',
        positiveText: '确定',
        negativeText: '取消',
        onPositiveClick: async () => {
            const {id} = log
            loading.value = true
            try {
                const res = await api.deleteById({id})
                if (res.code === 0) {
                    $message.success("删除促销活动成功！")
                    // await queryByPage()
                    await searchByCondition()
                } else {
                    $message.error(res.message)
                }
            } catch (err) {
                $message.error("删除促销活动失败！")
            } finally {
                loading.value = false
            }
        }
    })
}
const onDetailLog = async (log) => {
    const {id} = log
    await router.push({name: 'AdminLogDetail', params: {logId: id}});
}
const queryAdminList = async () => {
    loading.value = true
    try {
        const res = await api.findAllAdmin()
        if (res.code === 200) {
            res.data.map((item) => {
                admins.value.push({
                    label: item.name,
                    value: item.id
                })
            })
        } else {
          $message.error(res.message)
        }
    } catch (err) {
      $message.error("获取管理员信息失败！")
    } finally {
      loading.value = false
    }
}
const queryShopList = async () => {
  loading.value = true
  try {
    const res = await api.findAllShop()
    if (res.code === 200) {
      res.data.map((item) => {
        shops.value.push({
          label: item.name,
          value: item.id
        })
      })
    } else {
      $message.error(res.message)
    }
  } catch (err) {
    $message.error("获取店铺信息失败！")
  } finally {
    loading.value = false
  }
}
const queryStoreCommodityList = async () => {
  loading.value = true
  try {
    const res = await api.findAllProduct()
    if (res.code === 200) {
      res.data.map((item) => {
        console.log(item.name)
        storeCommodity.value.push({
          label: item.name,
          value: item.id
        })
      })
    } else {
      $message.error(res.message)
    }
  } catch (err) {
    $message.error("获取货物信息失败！")
  } finally {
    loading.value = false
  }
}
const queryByPage = async () => {
  loading.value = true
  try {
    const res = await api.findPageSalePromotionActivity(
        {
          params: {
            pageNum: paginationReactive.page,
            pageSize: paginationReactive.pageSize,
          }
        })
        if (res.code === 200) {
            total = res.data.total
            paginationReactive.itemCount = total
            const baseCount = (paginationReactive.page - 1)*paginationReactive.pageSize
            salePromotionActivityList.value = res.data.records.map((item,i)=>{
                return {...item,
                    colId: baseCount + i + 1,
                }
            })
            $message.success("获取促销活动成功！")
        } else {
            $message.error(res.message)
        }
    } catch (err) {
        $message.error("获取促销活动失败！")
    } finally {
        loading.value = false
    }
}
const rowKey = (rowData) => {
    return rowData.id
}
onMounted(() => {
  queryAdminList()
  queryByPage()
  queryShopList()
  queryStoreCommodityList()
})
</script>
<style scoped>
:deep(.n-data-table-th__title),
:deep(.n-data-table-td) {
    text-align: center;

}

:deep(.n-select) {
    width: 140px !important;
}

:deep(.two-line-description) {
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2; /* 控制显示的行数 */
    overflow: hidden;
}

</style>